#!/usr/bin/python3
#
# Copyright (C) 2012-2013 Gameloft
# alexandr.soor@gameloft.com
# nikolay.yakovlev@gameloft.com
# 13.03.2013

import os
import sys
import stat
import json
import shutil
import logging
logging.basicConfig(filename='log.log',level=logging.DEBUG)
import subprocess

from federation import Federation
import hashlib


def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    return md5.digest()


def start(auth, settings, save_to_svn, desc):
    clientid = open(
        os.path.join(
            settings.current_dir,
            'current_data/clientid'
        ), 'r').read().replace('\n', '')
    print(clientid)
    fed = Federation(
        clientid, settings.federation_user_name, settings.federation_password)

    from cryptTEA2 import CryptTEA
    CryptTEA(False)

    iris = fed.load_iris()
    iris.upload(os.path.join(settings.current_dir, 'out.tea'), settings.federation_iris_keyname)
    data = iris.get(settings.federation_iris_keyname)
    z = open(os.path.join(settings.current_dir, 'tmp.tea'), 'w+b')
    z.write(data)
    z.close()

    # if md5_for_file(open('out.tea','r+b')) != md5_for_file(open('tmp.tea','r+b')):
        # raise Exception('Iris Broken')

    shutil.copyfile(
        os.path.join(settings.current_dir, os.path.join(settings.current_dir, 'out.tea')),
        os.path.join(settings.current_dir, os.path.join(settings.current_dir, settings.svn_output_file))
    )

    if auth.is_admin() and save_to_svn == 'true':
        shell_text = """#!/bin/bash
cd /opt/bbreaker/uploader/federation/svn_data/
svn cleanup
svn up --accept mine-full
svn commit -m "* [auto] %s "
""" % desc.split('<br>')[0]
        fl = open('/opt/bbreaker/uploader/federation/runme.sh', 'w')
        fl.write(shell_text)
        fl.close()

        st = os.stat('/opt/bbreaker/uploader/federation/runme.sh')
        os.chmod('/opt/bbreaker/uploader/federation/runme.sh', st.st_mode | stat.S_IEXEC)

        # subprocess.call("/bin/bash /opt/bbreaker/uploader/federation/runme.sh", shell=True)
        os.system('/bin/bash /opt/bbreaker/uploader/federation/runme.sh')


    os.remove(os.path.join(settings.current_dir, 'out.tea'))
    os.remove(os.path.join(settings.current_dir, 'tmp.tea'))
